package com.cspg.ssss.controller;

import com.alibaba.fastjson.JSONObject;
import com.cspg.ssss.domain.CheckBatchInst;
import com.cspg.ssss.service.AnalysisService;
import com.cspg.ssss.service.CheckBatchService;
import com.cspg.ssss.util.DateUtil;
import com.cspg.ssss.vo.ResultVo;
import com.cspg.ssss.vo.ResultVoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/analysis")
public class AnalysisController {

    @Autowired
    AnalysisService analysisService;

    @Autowired
    CheckBatchService checkBatchService;

    /**
     * 将部门路径由/分隔改成->分隔，去掉超高压前缀
     * @param deptPath
     * @return
     */
    private String ConvertToDeptPath(String deptPath){
        if(deptPath.startsWith("超高压输电公司/") == false){
            return deptPath;
        }
        String newpath = deptPath.substring(8).replaceAll("/","->");
        return newpath;
    }

    /**
     * 将部门路径由->分隔改成/分隔，加上超高压前缀
     * @param deptPath
     * @return
     */
    private String ConvertDeptToPath(String deptPath){
        String newpath = deptPath.replaceAll("->","/");
        newpath = "超高压输电公司/"+newpath;
        return newpath;
    }

    private String getDwmc(String deptPath){
        String[] arrName = deptPath.split("/");
        return arrName[1];
    }

    /**
     * 部门打分情况分析
     * @param obj
     * @return
     */
    @PostMapping("/deptGradeAnalysis")
    public ResultVo deptGradeAnalysis(@RequestBody JSONObject obj){
        String user_dept = obj.getString("department_path");
        String npath = getDwmc(user_dept);//转换成->分隔的部门路径，用于数据库查询

        Map<String,Object> condition = new HashMap<String, Object>();

        CheckBatchInst batchInst = checkBatchService.getCurrentCheckBachInst(1);
        condition.put("batch_id",batchInst.getId());

        if(user_dept.indexOf("海口分局") != -1){
            condition.put("khbm_haikou","广州局->海口分局");
        }else {
            condition.put("dwmc",getDwmc(user_dept));
            condition.put("khbm","广州局->海口分局");
        }

        List<Map<String,Object>> retls = analysisService.getDeptBmmcGradeScoreAnalysis(condition);

        ResultVo retVo = null;
        retVo = ResultVoUtil.success("success",retls);
        return retVo;
    }

    /**
     * 部门打分情况跟踪
     * @param obj
     * @return
     */
    @PostMapping("/deptGradeMonitor")
    public ResultVo deptGradeMonitor(@RequestBody JSONObject obj){
        // 返回三部分内容，
        // 第一部分，当前阶段，阶段中文和标识 grade，feedback，review三个阶段，加分阶段用 add_apply,add_review来区分
        // 第二部分，当前阶段总体统计数据
        // 第三部分，当前阶段按照部门详细数据
        JSONObject retjson = new JSONObject();
        String user_dept = obj.getString("department_path");
        String npath = getDwmc(user_dept);//转换成->分隔的部门路径，用于数据库查询

        Map<String,Object> condition = new HashMap<String, Object>();

        CheckBatchInst batchInst = checkBatchService.getCurrentCheckBachInst(1);
        if(batchInst == null){
            ResultVo retErrorVo = null;
            retErrorVo = ResultVoUtil.error("9999","当前无批次!");
            return retErrorVo;
        }

        int nstage = batchInst.getCurrent_stage();
        String txtStage = "未知阶段";
        if(nstage == 0){
            txtStage = "评分阶段";
        }
        if(nstage == 1){
            txtStage = "确认及反馈阶段";
        }
        if(nstage == 2){
            txtStage = "终审阶段";
        }
        retjson.put("stage",txtStage);

        //判断加分处于哪个阶段
        JSONObject configObj = JSONObject.parseObject(batchInst.getConfig());
        int upload_days = configObj.getIntValue("upload_problem");
        int grade_days = configObj.getIntValue("grade");
        int feedback_days = configObj.getIntValue("feedback");
        int review_days = configObj.getIntValue("review");
        int add_score_apply_days = configObj.getIntValue("add_score_apply");
        int add_score_review_days = configObj.getIntValue("add_score_review");
        Date today = DateUtil.getCurrentDate();
        int period = DateUtil.workDaysPeriod(batchInst.getUpdate_time(),today);

        int period_addScore = DateUtil.workDaysPeriod(batchInst.getStart_date(),today);

        String addStage = "无阶段";
        if(period_addScore > 0 && period_addScore < add_score_apply_days){
            addStage = "加分申请阶段";
        }

        if(period_addScore > add_score_apply_days && period_addScore < add_score_apply_days + add_score_review_days){
            addStage = "加分申请最终审核阶段";
        }

        retjson.put("addStage",addStage);

        condition.put("batch_id",batchInst.getId());

        if(user_dept.indexOf("海口分局") != -1){
            condition.put("khbm_haikou","广州局->海口分局");
        }else {
            condition.put("dwmc",getDwmc(user_dept));
            condition.put("khbm","广州局->海口分局");
        }

        List<Map<String,Object>> resTotal = null;
        List<Map<String,Object>> resDetail = null;

        if(nstage == 0){
            resTotal = analysisService.getDeptGradeStageAnalysis(condition);
            condition.put("detail",true);
            resDetail = analysisService.getDeptGradeStageAnalysis(condition);
        }

        if(nstage == 1){
            resTotal = analysisService.getDeptFeedbackStageAnalysis(condition);
            condition.put("detail",true);
            resDetail = analysisService.getDeptFeedbackStageAnalysis(condition);
        }

        if(nstage == 2){
            resTotal = analysisService.getDeptReviewStageAnalysis(condition);
            condition.put("detail",true);
            resDetail = analysisService.getDeptReviewStageAnalysis(condition);
        }

        retjson.put("gradeTotal",resTotal);
        retjson.put("gradeDetail",resDetail);

        ResultVo retVo = null;
        retVo = ResultVoUtil.success("success",retjson);
        return retVo;
    }

    /**
     * 部门打分情况跟踪
     * @param obj
     * @return
     */
    @PostMapping("/deptRectifyMonitor")
    public ResultVo deptRectifyMonitor(@RequestBody JSONObject obj){
        JSONObject retjson = new JSONObject();

        int istotal = obj.getIntValue("total");
        Date startDate = new Date();
        Date endDate = new Date();
        if(istotal == 0) {
            String strStart = obj.getString("begin_date");
            String strEnd = obj.getString("end_date");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");


            try {
                startDate = df.parse(strStart);
                endDate = df.parse(strEnd);
            } catch (ParseException e) {
                ResultVo errVo = ResultVoUtil.error("9001", "参数解析错误");
                return errVo;
            }
        }
        String user_dept = obj.getString("department_path");
        String npath = getDwmc(user_dept);//转换成->分隔的部门路径，用于数据库查询

        Map<String,Object> condition = new HashMap<String, Object>();
        condition.put("istotal",istotal);
        if(istotal == 0){

            condition.put("begin_date",startDate);
            condition.put("end_date",endDate);
        }

        if(user_dept.indexOf("海口分局") != -1){
            condition.put("bmmc_haikou","广州局->海口分局");
        }else {
            condition.put("dwmc",getDwmc(user_dept));
            condition.put("bmmc","广州局->海口分局");
        }

        condition.put("rectify_type","company");
        List<Map<String,Object>> retcompanyStat = analysisService.findDeptRectifyAnalysis(condition);

        retjson.put("companyAnalysis",retcompanyStat);

        condition.put("detail",true);
        List<Map<String,Object>> retcompanyDetailStat = analysisService.findDeptRectifyAnalysis(condition);

        retjson.put("companyAnalysisDetail",retcompanyDetailStat);

        condition.remove("detail");

        condition.put("rectify_type","uncompany");
        List<Map<String,Object>> retuncompanyStat = analysisService.findDeptRectifyAnalysis(condition);
        retjson.put("uncompanyAnalysis",retuncompanyStat);

        condition.put("detail",true);
        List<Map<String,Object>> retuncompanyDetailStat = analysisService.findDeptRectifyAnalysis(condition);
        retjson.put("uncompanyAnalysisDetail",retuncompanyDetailStat);

        condition.remove("detail");

        condition.put("rectify_type","company");
        List<Map<String,Object>> retcompanyIntimeStat = analysisService.getDeptRectifyIntimeCountAnalysis(condition);

        retjson.put("companyIntimeAnalysis",retcompanyIntimeStat);

        condition.put("detail",true);
        List<Map<String,Object>> retcompanyIntimeDetailStat = analysisService.getDeptRectifyIntimeCountAnalysis(condition);

        retjson.put("companyIntimeAnalysisDetail",retcompanyIntimeDetailStat);

        condition.remove("detail");

        condition.put("rectify_type","uncompany");
        List<Map<String,Object>> retuncompanyIntimeStat = analysisService.getDeptRectifyIntimeCountAnalysis(condition);
        retjson.put("uncompanyIntimeAnalysis",retuncompanyIntimeStat);

        condition.put("detail",true);
        List<Map<String,Object>> retuncompanyIntimeDetailStat = analysisService.getDeptRectifyIntimeCountAnalysis(condition);
        retjson.put("uncompanyIntimeAnalysisDetail",retuncompanyIntimeDetailStat);

        ResultVo retVo = null;
        retVo = ResultVoUtil.success("success",retjson);
        return retVo;
    }

    /**
     * 根据条件获取某个字段分组列表
     * @param obj
     * @return
     */
    @PostMapping("/deptGroupList")
    public ResultVo deptGroupList(@RequestBody JSONObject obj){
        JSONObject retjson = new JSONObject();

        String user_dept = obj.getString("department_path");
        String npath = getDwmc(user_dept);//转换成->分隔的部门路径，用于数据库查询
        String field = obj.getString("group_field");

        Map<String,Object> condition = new HashMap<String, Object>();
        condition.put("dwmc",npath);
        condition.put("bmmc",npath);
        List<String> retList = analysisService.getDeptGroupList(condition);
        retjson.put("bmmc",retList);

        condition.remove("bmmc");
        condition.put("wtfxfs","wtfxfs");
        List<String> retList2 = analysisService.getDeptGroupList(condition);
        retjson.put("wtfxfs",retList2);

        ResultVo retVo = null;
        retVo = ResultVoUtil.success("success",retjson);
        return retVo;
    }

    /**
     * 单位对各部门考核问题统计分析数据
     * @param obj
     * @return
     */
    @PostMapping("/deptProblemAnalysis")
    public ResultVo deptProblemAnalysis(@RequestBody JSONObject obj){
        JSONObject retjson = new JSONObject();

        String user_dept = obj.getString("department_path");
        String npath = getDwmc(user_dept);//转换成->分隔的部门路径，用于数据库查询

        int istotal = obj.getIntValue("total");
        Date startDate = new Date();
        Date endDate = new Date();
        if(istotal == 0) {
            String strStart = obj.getString("begin_date");
            String strEnd = obj.getString("end_date");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");


            try {
                startDate = df.parse(strStart);
                endDate = df.parse(strEnd);
            } catch (ParseException e) {
                ResultVo errVo = ResultVoUtil.error("9001", "参数解析错误");
                return errVo;
            }
        }

        String wtfxfs = obj.getString("wtfxfs");
        String bmmc = obj.getString("bmmc");

        Map<String,Object> condition = new HashMap<String, Object>();
        condition.put("dwmc",npath);
        condition.put("istotal",istotal);
        if(istotal == 0){

            condition.put("begin_date",startDate);
            condition.put("end_date",endDate);
        }
        if(!wtfxfs.equalsIgnoreCase("all")){
            condition.put("wtfxfs",wtfxfs);
        }

        //按部门统计数量
        condition.put("field","bmmc");
        List<Map<String,Object>> bmmcCount = analysisService.getFieldCountByDept(condition);
        retjson.put("bmmc",bmmcCount);

        if(!bmmc.equalsIgnoreCase("all")){
            condition.put("bmmc",bmmc);
        }

        //专业类别
        condition.put("field","zylb");
        List<Map<String,Object>> zylbCount = analysisService.getFieldCountByDept(condition);
        retjson.put("zylb",zylbCount);

        //是否三老问题
        condition.put("field","sfslwt");
        List<Map<String,Object>> sfslwtCount = analysisService.getFieldCountByDept(condition);
        retjson.put("sfslwt",sfslwtCount);

        //是否主动暴露
        condition.put("field","sfzdbl");
        List<Map<String,Object>> sfzdblCount = analysisService.getFieldCountByDept(condition);
        retjson.put("sfzdbl",sfzdblCount);

        //业务事项
        condition.put("field","ywsx");
        List<Map<String,Object>> ywsxCount = analysisService.getFieldCountByDept(condition);
        retjson.put("ywsx",ywsxCount);

        //严重程度
        condition.put("field","wtyzcd");
        List<Map<String,Object>> wtyzcdCount = analysisService.getFieldCountByDept(condition);
        retjson.put("wtyzcd",wtyzcdCount);

        //所属层面
        condition.put("field","sscm");
        List<Map<String,Object>> sscmCount = analysisService.getFieldCountByDept(condition);
        retjson.put("sscm",sscmCount);

        //对应体系单元
        condition.put("field","dytxdy");
        List<Map<String,Object>> dytxdyCount = analysisService.getFieldCountByDept(condition);
        retjson.put("dytxdy",dytxdyCount);

        //对应体系要素
        condition.put("field","dytxys");
        List<Map<String,Object>> dytxysCount = analysisService.getFieldCountByDept(condition);
        retjson.put("dytxys",dytxysCount);

        condition.put("field","dytxys");
        condition.put("field2","dytxdy");
        List<Map<String,Object>> dytxysLinkCount = analysisService.getFieldCountByDept(condition);
        retjson.put("dytxysLink",dytxysLinkCount);


        ResultVo retVo = null;
        retVo = ResultVoUtil.success("success",retjson);
        return retVo;
    }

}
